#include "../include/drawer.h"
#include<QHBoxLayout>
#include<QLineEdit>
#include<QPushButton>
#include<QEvent>
#include<QFile>
#include<QMessageBox>
#include<QJsonDocument>
#include<QJsonObject>
#include<QJsonArray>
#include<QTreeWidgetItem>
#include<QFont>

Drawer::Drawer(QString account,QString password,QWidget *parent,Qt::WindowFlags f):QWidget(parent,f)
{
    this->setWindowTitle(tr("Myself QQ 2023"));
    this->setWindowIcon(QPixmap("://images/qq.png"));
    this->resize(300,700);
    this->setMinimumSize(this->size());
    this->setMaximumSize(this->size());

    m_account=account;
    m_password=password;
    friend_list=new QTreeWidget(this);
    seesion_list=new QListWidget(this);

    QWidget *head_portrait_Widget=this->init_head_portrait_Widget();
    QWidget *selectionbar=this->init_selectionbar();
    QListWidget *seesion_list=this->init_Seesion_widget(this->get_current_session());
    if(QFile(m_account+"/好友与好友分组.json").exists())
        friend_list=this->init_friend_list();

    head_portrait_Widget->setGeometry(QRect(QPoint(0,0),QSize(head_portrait_Widget->size())));
    selectionbar->setGeometry(QRect(QPoint(0,head_portrait_Widget->height()),QSize(selectionbar->size())));
    seesion_list->setGeometry(QRect(QPoint(0,head_portrait_Widget->height()+selectionbar->height()),
                                      QSize(this->size())));
    friend_list->setGeometry(seesion_list->geometry());


//    friend_list->setGeometry(QRect(QPoint(0,head_portrait_Widget->height()+selectionbar->height()+20),
//                                   QSize(this->size())));


//    toolBtn1=new QToolButton;
//    toolBtn1->setText(tr("水漂奇鼋"));
//    toolBtn1->setIcon(QPixmap("://images/spqy.png"));
//    toolBtn1->setIconSize(QPixmap("://images/spqy.png").size());
//    toolBtn1->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); //设置按钮的文字显示在图标旁边
//    toolBtn1->setAutoRaise(true);   //当鼠标离开时，按钮自动恢复成弹起状态

//    toolBtn2=new QToolButton;
//    toolBtn2->setText(tr("忆梦如澜"));
//    toolBtn2->setIcon(QPixmap("://images/ymrl.png"));
//    toolBtn2->setIconSize(QPixmap("://images/ymrl.png").size());
//    toolBtn2->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); //设置按钮的文字显示在图标旁边
//    toolBtn2->setAutoRaise(true);   //当鼠标离开时，按钮自动恢复成弹起状态

//    toolBtn3=new QToolButton;
//    toolBtn3->setText(tr("北京出版人"));
//    toolBtn3->setIcon(QPixmap("://images/qq.png"));
//    toolBtn3->setIconSize(QPixmap("://images/qq.png").size());
//    toolBtn3->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); //设置按钮的文字显示在图标旁边
//    toolBtn3->setAutoRaise(true);   //当鼠标离开时，按钮自动恢复成弹起状态

//    toolBtn4=new QToolButton;
//    toolBtn4->setText(tr("Cherry"));
//    toolBtn4->setIcon(QPixmap("://images/Cherry.png"));
//    toolBtn4->setIconSize(QPixmap("://images/qq.png").size());
//    toolBtn4->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); //设置按钮的文字显示在图标旁边
//    toolBtn4->setAutoRaise(true);   //当鼠标离开时，按钮自动恢复成弹起状态

//    toolBtn5=new QToolButton;
//    toolBtn5->setText(tr("淡然"));
//    toolBtn5->setIcon(QPixmap("://images/dr.png"));
//    toolBtn5->setIconSize(QPixmap("://images/dr.png").size());
//    toolBtn5->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); //设置按钮的文字显示在图标旁边
//    toolBtn5->setAutoRaise(true);   //当鼠标离开时，按钮自动恢复成弹起状态

//    toolBtn6=new QToolButton;
//    toolBtn6->setText(tr("娇娇girl"));
//    toolBtn6->setIcon(QPixmap("://images/jj.png"));
//    toolBtn6->setIconSize(QPixmap("://images/jj.png").size());
//    toolBtn6->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); //设置按钮的文字显示在图标旁边
//    toolBtn6->setAutoRaise(true);   //当鼠标离开时，按钮自动恢复成弹起状态

//    toolBtn7=new QToolButton;
//    toolBtn7->setText(tr("落水无痕"));
//    toolBtn7->setIcon(QPixmap("://images/lswh.png"));
//    toolBtn7->setIconSize(QPixmap("://images/lswh.png").size());
//    toolBtn7->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); //设置按钮的文字显示在图标旁边
//    toolBtn7->setAutoRaise(true);   //当鼠标离开时，按钮自动恢复成弹起状态

//    toolBtn8=new QToolButton;
//    toolBtn8->setText(tr("青墨暖暖"));
//    toolBtn8->setIcon(QPixmap("://images/qmnn.png"));
//    toolBtn8->setIconSize(QPixmap("://images/qmnn.png").size());
//    toolBtn8->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); //设置按钮的文字显示在图标旁边
//    toolBtn8->setAutoRaise(true);   //当鼠标离开时，按钮自动恢复成弹起状态

//    toolBtn9=new QToolButton;
//    toolBtn9->setText(tr("无语"));
//    toolBtn9->setIcon(QPixmap("://images/wy.png"));
//    toolBtn9->setIconSize(QPixmap("://images/wy.png").size());
//    toolBtn9->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); //设置按钮的文字显示在图标旁边
//    toolBtn9->setAutoRaise(true);   //当鼠标离开时，按钮自动恢复成弹起状态

//    QGroupBox *groupBox=new QGroupBox;
//    QVBoxLayout *layout=new QVBoxLayout(groupBox);

//    layout->setContentsMargins(20,20,20,20);
//    layout->setAlignment(Qt::AlignLeft);
//    layout->addWidget(toolBtn1);
//    layout->addWidget(toolBtn2);
//    layout->addWidget(toolBtn3);
//    layout->addWidget(toolBtn4);
//    layout->addWidget(toolBtn5);
//    layout->addWidget(toolBtn6);
//    layout->addWidget(toolBtn7);
//    layout->addWidget(toolBtn8);
//    layout->addWidget(toolBtn9);
//    layout->addStretch();
//    this->addItem(groupBox,tr("群成员"));


}

bool Drawer::eventFilter(QObject *watched, QEvent *event)
{
    QLineEdit *usrNameLineEdit=this->findChild<QLineEdit *>("usrNameLineEdit");
    const QString post_text=usrNameLineEdit->text();
    if(event->type()==QEvent::MouseButtonDblClick&&usrNameLineEdit==watched){
        if(usrNameLineEdit!=nullptr){
            usrNameLineEdit->setFocusPolicy(Qt::FocusPolicy::StrongFocus);
        }
    }
    if(event->type()!=QEvent::MouseButtonDblClick&&usrNameLineEdit!=watched){
        usrNameLineEdit->setText(post_text);
    }
    return QWidget::eventFilter(watched,event);
}

void Drawer::showChatWidget(QTreeWidgetItem *item, int column)
{
    if(item->childCount()==0&&item->parent()==nullptr)
        return;

}


void Drawer::updateAndSaveName(const QString& before_modify_usrName,const QString& after_modify_usrName)
{
    QLineEdit *usrNameLineEdit=this->findChild<QLineEdit *>("usrNameLineEdit");
    if(usrNameLineEdit->text()==before_modify_usrName) return;
    QMessageBox mb(QMessageBox::Icon::Question,tr("保存昵称"),tr("是否保存？"));
    auto isSaveBtn=mb.addButton(QMessageBox::Save);
    mb.addButton(QMessageBox::Cancel);
    mb.exec();
    if(mb.clickedButton()==isSaveBtn){
        const QString dir=m_account+"/usrName.txt";
        QFile *file=new QFile(dir);
        if(file->open(QFile::WriteOnly)){
            file->write(after_modify_usrName.toUtf8());
            file->close();
        }
        else{
            if(usrNameLineEdit)
                usrNameLineEdit->setText(before_modify_usrName);
        }
    }
    else{
        if(usrNameLineEdit)
            usrNameLineEdit->setText(before_modify_usrName);
    }
}

QWidget *Drawer::init_head_portrait_Widget()
{
    QWidget *head_portrait_domain=new QWidget(this,Qt::WindowType::FramelessWindowHint);
    QWidget *head_portrait=new QWidget(head_portrait_domain,Qt::WindowType::FramelessWindowHint);
    QLineEdit *usrNameLineEdit=new QLineEdit(m_account,head_portrait_domain);
    head_portrait_domain->resize(this->width(),this->height()/4);

    head_portrait_domain->setObjectName("head_portrait_domain");
    head_portrait_domain->setAutoFillBackground(true);
    QPalette pal=head_portrait_domain->palette();
    QPixmap *domain_pix=new QPixmap(":/bg/images/bg/wy.png");
    *domain_pix=domain_pix->scaled(head_portrait_domain->size(),Qt::AspectRatioMode::IgnoreAspectRatio);
    pal.setBrush(QPalette::Window,QBrush(*domain_pix));
    head_portrait_domain->setPalette(pal);

    head_portrait->setAutoFillBackground(true);
    head_portrait->setGeometry(10,head_portrait_domain->height()/3,70,70);
    head_portrait->setMask(QRegion(0,0,head_portrait->width(),head_portrait->height(),QRegion::Ellipse));
    QPalette pal2=head_portrait->palette();
    pal2.setBrush(QPalette::Window,QBrush(QPixmap("://images/qq.png").scaled(head_portrait->size(),
                                                                              Qt::AspectRatioMode::IgnoreAspectRatio)));
    head_portrait->setPalette(pal2);

    usrNameLineEdit->setGeometry(head_portrait->x()+head_portrait->width()+20,
                              head_portrait->y()+head_portrait->height()/2-usrNameLineEdit->height()/2-30,
                              usrNameLineEdit->width(),usrNameLineEdit->height());
    QFile *file=new QFile(m_account+"/usrName.txt");
    if(file->exists()&&file->open(QFile::ReadOnly)&&file->size()!=0){
        const char *usrName=file->readLine();
        usrNameLineEdit->setText(usrName);
        file->close();
    }
    usrNameLineEdit->setObjectName("usrNameLineEdit");
    usrNameLineEdit->setMaxLength(10);
    QPalette namePal=usrNameLineEdit->palette();
    namePal.setColor(QPalette::Base,QColor(0,0,0,0));
    namePal.setColor(QPalette::Text,QColor(205,226,178,255));
    usrNameLineEdit->setPalette(namePal);
    usrNameLineEdit->setAutoFillBackground(true);
    //usrNameLineEdit->setStyleSheet("background-color: rgba(255, 255, 255, 0);");
    usrNameLineEdit->setFrame(false);
    usrNameLineEdit->setFocusPolicy(Qt::NoFocus);
    const QString curUserName=usrNameLineEdit->text();
    usrNameLineEdit->installEventFilter(this);
    connect(usrNameLineEdit,&QLineEdit::editingFinished,
            this,[curUserName,usrNameLineEdit,this](){
                                            emit this->emitUserName(curUserName,usrNameLineEdit->text());
                                            usrNameLineEdit->clearFocus();});
    connect(this,SIGNAL(emitUserName(QString,QString)),this,SLOT(updateAndSaveName(QString,QString)));

    return head_portrait_domain;
}

QWidget *Drawer::init_selectionbar()
{
    QWidget *selectionbar=new QWidget(this,Qt::WindowType::FramelessWindowHint);
    QHBoxLayout *layout=new QHBoxLayout(selectionbar);
    QPushButton *msgBtn=new QPushButton(tr("消息"),selectionbar);
    QPushButton *contact_person=new QPushButton(tr("联系人"),selectionbar);
    //qDebug()<<selectionbar->size()<<" : "<<layout->geometry()<<" : "<<msgBtn->size();

    selectionbar->resize(this->width(),30);
    msgBtn->setGeometry(0,0,selectionbar->width()/2,selectionbar->height());
    contact_person->setGeometry(selectionbar->width()/2,0,msgBtn->width(),msgBtn->height());
    msgBtn->setFlat(true);
    contact_person->setFlat(true);

    connect(msgBtn,&QPushButton::clicked,
            this,[this]{this->friend_list->setHidden(true);
                        this->seesion_list->setHidden(false);
            });
    connect(contact_person,&QPushButton::clicked,this,
            [this]{this->seesion_list->setHidden(true);
                   this->friend_list->setHidden(false);
            });

    return selectionbar;
}

QListWidget *Drawer::init_Seesion_widget(const QStringList &seesion_name)
{
    if(seesion_list->count()==0){
        seesion_list->addItem(tr("当前没有会话！"));
        seesion_list->setSelectionMode(QAbstractItemView::NoSelection);
        QListWidgetItem *curItem=seesion_list->item(0);
        curItem->setTextAlignment(Qt::AlignmentFlag::AlignCenter);
        curItem->setFlags(Qt::ItemFlag::NoItemFlags);
        return seesion_list;
    }
    if(seesion_name.isEmpty())  return seesion_list;
    const QString iconDdir=m_account+"/my_head_portrait";
    for(int i=0;i!=seesion_name.size();i++){
        QListWidgetItem *friendid=new QListWidgetItem(QIcon(iconDdir+"/qq.png"),seesion_name[i]);
        seesion_list->addItem(friendid);
    }
    return seesion_list;
}

QTreeWidget *Drawer::init_friend_list()
{
    friend_list->clear();
    friend_list->setHeaderHidden(true);
    QFile *file=new QFile(m_account+"/好友与好友分组.json");
    if(!file->open(QFile::ReadOnly)){
        delete file;
        return friend_list;
    }

    QString jsonList=QString::fromUtf8(file->readAll());
    QJsonParseError *error;
    QJsonDocument jd=QJsonDocument::fromJson(jsonList.toUtf8(),error);
    //qDebug()<<error->errorString();
    QJsonObject jo=jd.object();
    QStringList grounping=jo.keys();

    for(auto p=grounping.begin();p!=grounping.end();p++){
        int i=p-grounping.begin();
        QTreeWidgetItem* grounp=new QTreeWidgetItem(friend_list);
        grounp->setChildIndicatorPolicy(QTreeWidgetItem::ShowIndicator);
        grounp->setText(0,grounping[i]);
        grounp->setFont(0,QFont(grounp->font(0).family(),12));
        auto value=jo.value(grounping[i]);
        if(value.isArray()){
            QJsonArray array=value.toArray();
            if(array.isEmpty()) continue;
            for(auto pp=array.begin();pp!=array.end();pp++){
                if(!(*pp).isString())   continue;
                QTreeWidgetItem* ggrounp=new QTreeWidgetItem(grounp);
                ggrounp->setFont(0,QFont(ggrounp->font(0).family(),12));
                ggrounp->setText(0,pp->toString());
            }
        }
    }
    friend_list->setFrameShape(QFrame::Box);
    friend_list->setFrameShadow(QFrame::Raised);

    connect(friend_list,SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)),this,SLOT(showChatWidget(QTreeWidgetItem*,int)));
    file->close();
    return friend_list;
}

const QStringList Drawer::get_current_session()
{
    return QStringList{};
}

const QStringList Drawer::get_friends_name()
{
    return QStringList();
}
